A quick hack to set the timezone for a Vagrant VM in Ubuntu
I wanted to make sure that the Vagrant VM I was building was always in sync with the host timezone. After poking about and not finding any real elegant way to do it, I came up with the following hack for an Ubuntu VM.
NOTE: This only works if the VM is set to UTC
in /etc/timezone
The snippet:
Vagrant.configure(2) do |config|
# Set the timezone to the host timezone
require 'time'
timezone = 'Etc/GMT' + ((Time.zone_offset(Time.now.zone)/60)/60).to_s
config.vm.provision :shell, :inline => "if [ $(grep -c UTC /etc/timezone) -gt 0 ]; then echo \"#{timezone}\" | sudo tee /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata; fi"
end
Using Ruby's time
class, the timezone variable is assigned the string of Etc/GMT-#
where # is the calculated timezone offset cast to a string.
Upon boot of the vm, grep will check to see if /etc/timezone
is set to UTC
and if so, put the value of the timezone variable in /etc/timezone
, then call dpkg-reconfigure
to update the OS to use the value set in /etc/timezone
.
Written by Gavin M. Roy
Related protips
1 Response
Also some multi-string syntax makes things easier to read/modify later:
config.vm.provision :shell, :inline => %Q(
if [ $(grep -c UTC /etc/timezone) -gt 0 ]
then echo "#{timezone}" | sudo tee /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata
fi
)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Vagrant
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#